import { BrowserWindow } from "@electron/remote";
import { Container } from "typedi";
import { ElMessage } from "@chulei-ui/element-plus";
import { esi } from "../repositories";
import { AuthService } from "../repositories/AuthService";
export const useAuth = () => {
  const authService = Container.get(AuthService);
  const getAuthCode = async () => {
    const authUrl = await esi.auth.authUrl([
      "esi-contracts.read_character_contracts.v1",
      "esi-assets.read_assets.v1",
      "esi-universe.read_structures.v1",
      "esi-planets.manage_planets.v1",
    ]);

    return new Promise<string>((resolve, reject) => {
      const authWindow = new BrowserWindow({
        width: 800,
        height: 600,
        autoHideMenuBar: true,
      });
      const cleanAuthWindow = new BrowserWindow({
        width: 0,
        height: 0,
      });
      cleanAuthWindow.hide();
      cleanAuthWindow.loadURL("https://login.evepc.163.com/account/logoff").then(() => {
        cleanAuthWindow.destroy();
        const handler = setTimeout(() => {
          authWindow.destroy();
          reject("auth timeout");
        }, 1000 * 60);

        authWindow
          .loadURL(authUrl)
          .then(() => {
            authWindow.webContents.on("did-navigate", (_, url) => {
              const params = new URLSearchParams(new URL(url).search);
              const code = params.get("code");
              if (code) {
                clearTimeout(handler);
                authWindow.destroy();
                resolve(code);
              }
            });
            authWindow.on("close", () => {
              ElMessage.error("主动取消授权");
              reject("取消授权");
            });
          })
          .catch((e) => {
            ElMessage.error("授权页面打开失败请关闭后重试");
            reject(e);
          });
      });
    });
  };

  const getRefreshToken = async (esiCode: string) => {
    const token = await esi.auth.getTokenFromESICode(esiCode);
    if (!token) {
      throw new Error(`esi code fetch token fail ${esiCode} please retry`);
    }
    const authUser = esi.auth.getTokenInfo(token);
    await authService.addAuthRole(token, authUser);
  };
  return { getAuthCode, getRefreshToken };
};
